package com.szholly.pro.watergas_server.ps.android.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.android.common.CommonSqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.NonNullUtil;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.controller.AndroidPageInfo;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

/**
 * 报警信息
 * 
 * 2017/6/12 <br/>
 *
 * @author Joey Huang QQ:273179370）
 */
@Service
public class MoveDataWarnService {
	public Map<String, Object> getSurfaceWarnList(String userId, String unitName, String stationId, String isRecover, String startTime,
			String endTime, int pageIndex) throws Exception {
		String groupCode = CommonSqlUtils.getGroupCode(userId);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String stationSql = "select distinct t.station_id\n"
				+ " from OPERATION_GROUP_STATION_ASSO t\n"
				+ " left join BC_SITE_INFO t1\n"
				+ "   on t.station_id = t1.code\n"
				+ " left join DATA_DEFULATDOMAIN t2\n"
				+ "   on t2.S_DOMAINNAME = '政区'\n"
				+ "  and length(t2.s_id) = '2'\n"
				+ "  and SUBSTR(t.station_id, 3, 2) = t2.s_id\n"
				+ "where 1 = 1\n";
		if (!StringUtils.IsNullOrSpace(stationId)) {
			parms.add(new GlobalParameter("stationId", stationId));
			stationSql += "  and t.station_id = @stationId\n";
		}
		if (!StringUtils.IsNullOrSpace(groupCode)) {
			parms.add(new GlobalParameter("groupCode", groupCode));
			stationSql += "  and t.operation_group_id = @groupCode\n";
		}
		if (!StringUtils.IsNullOrSpace(unitName)) {
			parms.add(new GlobalParameter("unitName", unitName));
			stationSql += "  and t2.S_DOMAINCAPTION = @unitName\n";
		}
		stationSql += "  and t1.station_category = '1'\n";
		return getWarnList(stationSql, parms, isRecover, startTime, endTime, pageIndex);
	}

	public Map<String, Object> getSewageWarnList(String userId, String unitName, String stationId, String isRecover, String startTime,
			String endTime, int pageIndex) throws Exception {
		String groupCode = CommonSqlUtils.getGroupCode(userId);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String stationSql = "select distinct t.station_id\n"
				+ " from OPERATION_GROUP_STATION_ASSO t\n"
				+ " left join BC_SITE_INFO t1\n"
				+ "   on t.station_id = t1.code\n"
				+ " left join DATA_DEFULATDOMAIN t2\n"
				+ "   on t2.S_DOMAINNAME = '政区'\n"
				+ "  and length(t2.s_id) = '2'\n"
				+ "  and SUBSTR(t.station_id, 3, 2) = t2.s_id\n"
				+ "where 1 = 1\n";
		if (!StringUtils.IsNullOrSpace(stationId)) {
			parms.add(new GlobalParameter("stationId", stationId));
			stationSql += "  and t.station_id = @stationId\n";
		}
		if (!StringUtils.IsNullOrSpace(groupCode)) {
			parms.add(new GlobalParameter("groupCode", groupCode));
			stationSql += "  and t.operation_group_id = @groupCode\n";
		}
		if (!StringUtils.IsNullOrSpace(unitName)) {
			parms.add(new GlobalParameter("unitName", unitName));
			stationSql += "  and t2.S_DOMAINCAPTION = @unitName\n";
		}
		stationSql += "  and t1.station_category = '0'\n";
		return getWarnList(stationSql, parms, isRecover, startTime, endTime, pageIndex);
	}

	public Map<String, Object> getZhWarnList(String userId, String unitName, String stationId, String isRecover, String startTime, String endTime,
			int pageIndex) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("userId", userId));
		String stationSql = "select distinct t.station_code\n"
				+ "          from OC_ROLE_SITE_PRIVILEGE t\n"
				+ "         inner join safe_userrole t1\n"
				+ "            on t1.s_userid =\n"
				+ "               @userId\n"
				+ "           and t.role_id = t1.s_roleid\n"
				+ "         where t.station_code is not null\n";
		if (!StringUtils.IsNullOrSpace(stationId)) {
			parms.add(new GlobalParameter("stationId", stationId));
			stationSql+=" and t.station_code = @stationId";
		}		
		return getWarnList(stationSql, parms, isRecover, startTime, endTime, pageIndex);
	}

	// 获取历史数据界面初始化数据
	public Map<String, Object> getAllWarnList(String groupCode, String unitName, String stationId, String isRecover, String startTime, String endTime,
			int pageIndex) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String stationSql = "select distinct t.station_id\n"
				+ " from OPERATION_GROUP_STATION_ASSO t\n"
				+ " left join BC_SITE_INFO t1\n"
				+ "   on t.station_id = t1.code\n"
				+ " left join DATA_DEFULATDOMAIN t2\n"
				+ "   on t2.S_DOMAINNAME = '政区'\n"
				+ "  and length(t2.s_id) = '2'\n"
				+ "  and SUBSTR(t.station_id, 3, 2) = t2.s_id\n"
				+ "where 1 = 1\n";
		if (!StringUtils.IsNullOrSpace(stationId)) {
			parms.add(new GlobalParameter("stationId", stationId));
			stationSql += "  and t.station_id = @stationId\n";
		}
		if (!StringUtils.IsNullOrSpace(groupCode)) {
			parms.add(new GlobalParameter("groupCode", groupCode));
			stationSql += "  and t.operation_group_id = @groupCode\n";
		}
		if (!StringUtils.IsNullOrSpace(unitName)) {
			parms.add(new GlobalParameter("unitName", unitName));
			stationSql += "  and t2.S_DOMAINCAPTION = @unitName\n";
		}
		stationSql += "  and t1.station_category in ('0','1')\n";
		return getWarnList(stationSql, parms, isRecover, startTime, endTime, pageIndex);
	}

	// 获取历史数据界面初始化数据
	public Map<String, Object> getWarnList(String stationSql, List<GlobalParameter> parms, String isRecover, String startTime, String endTime,
			int pageIndex) throws Exception {
		ValidUtils.hasText(startTime, "获取报警信息失败，开始时间不能为空");
		ValidUtils.hasText(startTime, "获取报警信息失败，结束不能为空");
		parms.add(new GlobalParameter("startTime", startTime));
		parms.add(new GlobalParameter("endTime", endTime));
		String warnSql = "select t.station_code \"stationId\",\n"
				+ "       t.is_recover \"isRecover\",\n"
				+ "       t1.S_DOMAINCAPTION \"alarmType\",\n"
				+ "       t2.S_DOMAINCAPTION \"parameterName\",\n"
				+ "       t.continue_time || '(分钟)' \"continueTime\",\n"
				+ "       t.alarm_value \"alarmValue\",\n"
				+ "       to_char(t.start_time, 'yyyy-mm-dd hh24:mi:ss') \"startTime\",\n"
				+ "       to_char(t.recover_time, 'yyyy-mm-dd hh24:mi:ss') \"recoverTime\",\n"
				+ "       t2.S_UNIT\n"
				+ "  from OP_ALAR_INFO t\n"
				+ "  left join data_defulatdomain t1\n"
				+ "    on t1.S_DOMAINNAME = '报警类型'\n"
				+ "   and t1.s_domaincode = t.type\n"
				+ "  left join data_defulatdomain t2\n"
				+ "    on t2.S_DOMAINNAME = 'MONITOR_PARAM'\n"
				+ "   and t2.s_domaincode = t.param\n"
				+ " where 1 = 1\n"
				+ "   and t.continue_time > 1\n";
		// 报警是否恢复
		if ("1".equals(isRecover)) {
			warnSql += "   and t.IS_RECOVER = '1'\n";
		} else if ("0".equals(isRecover)) {
			// 0和2都表示报警中
			warnSql += "   and t.IS_RECOVER <> '1'\n";
		}
		warnSql += "   and t.station_code in (" + stationSql + ")\n";
		warnSql += "   and t.start_time between to_date(@startTime, 'yyyy-mm-dd') and\n"
				+ "       to_date(@endTime, 'yyyy-mm-dd') + 1\n"
				+ "  order by t.start_time desc";

		int rowsCount = SqlUtils.getRowsCount(warnSql, parms);
		int upRowLimit = pageIndex * 25;
		int downRowLimit = (pageIndex - 1) * 25;
		parms.add(new GlobalParameter("upRowLimit", upRowLimit));
		parms.add(new GlobalParameter("downRowLimit", downRowLimit));
		String pageSql = "select * from (\n"
				+ "select t.*,ROWNUM oracle_rn from (\n"
				+ warnSql
				+ ") t where ROWNUM <=@upRowLimit\n"
				+ ") t where t.oracle_rn >@downRowLimit";
		List<RowBase> rows = DataUtil.getSelectRows(pageSql, parms);
		// 处理数据 移除没用的字段oracle_rn，修改原有的科学计数法
		if (!CollectionUtils.isEmpty(rows)) {
			for (RowBase rowBase : rows) {
				String unit = (String) rowBase.get("S_UNIT");
				String alarmValue = (String) rowBase.get("alarmValue");
				rowBase.remove("ORACLE_RN");
				rowBase.remove("S_UNIT");
				rowBase.put("alarmValue", getAlarmValueString(alarmValue, unit));
			}
		}
		AndroidPageInfo pageInfo = AndroidPageInfo.create(rowsCount, 25, pageIndex);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("data", NonNullUtil.toList(rows));
		resultMap.put("pageInfo", pageInfo);
		return resultMap;
	}

	private static String getAlarmValueString(String value, String unit) {
		try {
			BigDecimal bd = new BigDecimal(value);
			return bd.toPlainString() + unit;
		} catch (Exception e) {
			return value;
		}
	}
}
